import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
# Create your views here.

from book.models import BookInfo


class BookListView(View):
    """
    查询所有图书、增加图书
    """

    def get(self, request):
        """
        查询所有图书
        路由：GET /books/
        """
        queryset = BookInfo.objects.all()
        book_list = []
        for book in queryset:
            book_list.append({
                'id': book.id,
                'name': book.name,
                'pub_date': book.pub_date
            })
        return JsonResponse(book_list, safe=False)

    def post(self, request):
        """
        新增图书
        路由：POST /books/
        """
        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book = BookInfo.objects.create(
            name=book_dict.get('name'),
            pub_date=book_dict.get('pub_date')
        )

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        }, safe=False)


class BookDetailView(View):
    """
    获取单个图书信息
    修改图书信息
    删除图书
    """

    def get(self, request, pk):
        """
        获取单个图书信息
        路由： GET  /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({}, status=404)

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        })

    def put(self, request, pk):
        """
        修改图书信息
        路由： PUT  /books/<pk>
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({}, status=404)

        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book.name = book_dict.get('name')
        book.pub_date = book_dict.get('pub_date')
        book.save()

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        })

    def delete(self, request, pk):
        """
        删除图书
        路由： DELETE /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({}, status=404)

        book.delete()

        return JsonResponse({}, status=204)


# ******************************
# 一级视图
from rest_framework.views import APIView
from book.serializers import BookInfoModelSerializer
from rest_framework.response import Response


class BookListAPIView(APIView):

    def get(self, request):
        book = BookInfo.objects.all()
        slz = BookInfoModelSerializer(instance=book, many=True)
        # slz.is_valid(raise_exception=True)
        return Response(slz.data)

    def post(self, request):

        data = request.data
        slz = BookInfoModelSerializer(data=data)
        if slz.is_valid(raise_exception=True):
            slz.save()
            return Response(slz.data)
        else:
            return Response({'msg': '保存失败'})


# ******************二级视图(GenericAPIView)*************************
from rest_framework.generics import GenericAPIView
from rest_framework import status


class BookInfoGenericAPIView(GenericAPIView):
    """列表视图"""
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializer

    # 查询所有数据
    def get(self, request):
        books = self.get_queryset()

        slz = self.get_serializer(books, many=True)

        return Response(slz.data)

    # 新增数据
    def post(self, request):
        data = request.data
        slz = self.get_serializer(data=data)
        if slz.is_valid():
            slz.save()
            return Response(slz.data)


class BookInfoDetailGenericAPIView(GenericAPIView):
    """详情视图"""
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializer
    lookup_field = 'id'

    # 查询单个数据
    def get(self, request, id):
        book = self.get_object()
        slz = self.get_serializer(book)
        return Response(slz.data)

    # 修改数据
    def put(self, request, id):
        book = self.get_object()
        data = request.data
        slz = self.get_serializer(instance=book, data=data)
        slz.is_valid()
        slz.save()
        return Response(slz.data)

    def delete(self, request, id):
        book = self.get_object()
        book.delete()
        # return Response(status=status.HTTP_204_NO_CONTENT)
        return Response({'msg': '删除成功'})


# *************GenericAPIView配合Mixin使用***********************
from rest_framework.mixins import ListModelMixin, CreateModelMixin


class BookInfoGenericMixinAPIView(GenericAPIView, ListModelMixin, CreateModelMixin):
    """列表视图"""
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializer

    def get(self, request):
        return self.list(request)

    def post(self, request):
        return self.create(request)


from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin

"""详情视图"""


class BookInfoDetailGenericMixinAPIVIiew(GenericAPIView,
                                         RetrieveModelMixin,
                                         UpdateModelMixin,
                                         DestroyModelMixin):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializer
    lookup_field = 'id'

    def get(self, request, id):
        return self.retrieve(request)

    def put(self, request, id):
        return self.update(request)

    def delete(self, request, id):
        return self.destroy(request)


# ************子类视图***********************
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView


class BookInfoListCreaetAPIView(ListCreateAPIView):
    """列表视图"""
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializer

class BookInfoDetailListCreaetAPIView(RetrieveUpdateDestroyAPIView):
    """详情视图"""
    lookup_field = 'id'
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializer

# *********************视图集**********************
from rest_framework.viewsets import ModelViewSet
class BookInfoModelViewSet(ModelViewSet):

    queryset = BookInfo.objects.all()

    serializer_class = BookInfoModelSerializer

# **************高级功能******************
from book.models import PeopleInfo
from rest_framework.generics import GenericAPIView
from book.serializers import PeopleInfoModelSerializer
from rest_framework.permissions import AllowAny,IsAuthenticatedOrReadOnly,IsAdminUser,IsAuthenticated
# 分页
from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination

class PageNum(PageNumberPagination):

    # 开关 默认值一页显示5条数据
    page_size = 5
    # 重命名
    page_size_query_param = 'ps'
    # 最大值
    max_page_size = 20

class PeopleInfoModelViewSet(ModelViewSet):

    # 给视图 单独设置权限
    # permission_classes = [AllowAny]

    #单独设置分页类
    pagination_class = PageNum

    # queryset = PeopleInfo.objects.all()
    # 或者
    def get_queryset(self):
        return PeopleInfo.objects.all()


    # serializer_class = PeopleInfoModelSerializer
    # 或者
    def get_serializer_class(self):
        return PeopleInfoModelSerializer